<?php

include_once('php/mt.php');
include_once('php/lib/MTUtil.php');

function test_instance_of($param) {
	$mt = new MT(1, $param['mt-config.cgi']);

	$ctx =& $mt->context();
	$db = $mt->db();
	$ctx->mt->db = &$db;

	$mt->init_plugins();

	return $mt;
}

function test_template_build($mt, $string) {
	$mt->db->savedqueries = array();

	$ctx =& $mt->context();

    if ($ctx->_compile_source('evaluated template', $string, $_var_compiled)) {
        ob_start();
        $ctx->_eval('?>' . $_var_compiled);
        $_contents = ob_get_contents();
        ob_end_clean();
		return array(
			'error' => 0,
			'result' => $_contents,
		);
    } else {
		return array(
			'error' => 1,
			'result' => $ctx->error("Error compiling template module '$module'"),
		);
    }
}

function _test_load_object_in_hash(&$hash) {
	global $mt;
	$ctx =& $mt->context();
	$db =& $ctx->mt->db;
	$keys = array_keys($hash);
	foreach ($keys as $k) {
		$v =& $hash[$k];
		if (is_array($v)) {
			_test_load_object_in_hash($v);
		}

		if (! $v && $hash[$k . '_id']) {
			$meth = 'fetch_' . $k;
			if (method_exists($db, $meth)) {
				if (is_array($hash[$k . '_id'])) {
					$hash[$k] = array();
					foreach ($hash[$k . '_id'] as $id) {
						$obj = $db->$meth($id);
						if ($obj) {
							$hash[$k][] = $obj;
						}
					}
				}
				else {
					$hash[$k] = $db->$meth($hash[$k . '_id']);
				}
			}
		}
	}
}

function test_template_load_context($json) {
	global $mt;
	$ctx =& $mt->context();
	$list = json_decode($json, true);
	$keys = array_keys($list);
	foreach ($keys as $i) {
		$h =& $list[$i];
		if (is_array($h)) {
			_test_load_object_in_hash($h);
		}

		if (! empty($h['__stash'])) {
			foreach ($h['__stash'] as $k => $v) {
				$ctx->stash($k, $v);
			}
		}

		if (! empty($h['__stash']['vars'])) {
			foreach ($h['__stash']['vars'] as $k => $v) {
				$ctx->__stash['vars'][$k] = $v;
			}
		}
	}

	return true;
}

function test_template_param($json) {
	global $mt;
	$ctx =& $mt->context();
	$hash = json_decode($json);
	_test_load_object_in_hash($hash);
	foreach ($hash as $k => $v) {
		$ctx->__stash['vars'][$k] = $v;
	}

	return true;
}

function test_run($param = array()) {
	global $mt;
	$mt = test_instance_of($param);
	$read = fopen('php://stdin', 'r');
	$write = fopen('php://stdout', 'w');

	stream_set_blocking($read, 1);
	stream_set_write_buffer($write, 0);

	while ($str = fgets($read, 1024)) {
		$ret = eval('return ' . $str);
		if (is_array($ret)) {
			fwrite($write, json_encode($ret) . "\n");
		}
	}
}


?>
